var syncstate = "";

//gid, uid, groupname are globals in index.html

var User = {
  userName: "",
  groupName: "",
  userLogin: 0,
  uid: 0,
  userAuth: 0, //0 = user has not authorized the app, 1 = authorized
  userType: "",

  checkLogin: function() {
    var url = "";
    var gid = LB.Utils.getRequestParam('gid');

    if(gid) {
      url = "/login?gid=" + gid;
    }
    else {
      url = "/login";
    }
    
    $.ajax({
      url: url,
      cache: false,
      async: false,
      success: function(html){
        //XXX appengine instance issue, which 
        //give zero byte response the first time this
        //request is made since the instance is not setup
        //so fetch is again after some time
        //fetch the contacts only we know that the instance is
        //up, which is indicated with a non-zero response
        if(html === "") {
          setTimeout("User.checkLogin()", 1000);
          $("#hdrmsg").html("Not signed in");
        }
        else {
          $("#hdrmsg").html(html);
          setTimeout("User.fetchContacts()", 500);
        }
        if(html.match("Sign In")) {
          User.userLogin = 0;
        }
        else if(html.match("Sign Out")) {
          User.userLogin = 1;
          var arr = html.split(" ");
          User.userName = arr[1];
        }
      },
      error: function(error) {
        LB.UI.alert("Login Error");
      }
    });
  },

  fetchDocs: function() {
    if(User.userLogin === 0) {
      return 0;
    }

    $.ajax({
      url: "/fetch?service=docs",
      cache: false,
      dataType: "json",
      success: function(obj){
        var i = 0;
        var str;

        if(obj.msg === "Success") {
          str = '<select id="contacts" class="multiselect" multiple="multiple" name="contacts[]">';
          for(i=0; i<obj.data.length; i++) {
            str += '<option value=' + obj.data[i].title + '>' + 
                obj.data[i].title + '</option>';
          }
          str += '</select>';

          $("#sharecontacts").html(str);
          writeDebug(obj.data.length, 3);
          User.userAuth = 1;
        }
        else if(obj.msg === "Authorize") {
          $("#hdrmsg").html("Hello, " + User.userName + " " + obj['data']);
          User.userAuth = 0;
        }
      },
      error: function(error) {
        alert("Could not fetch contacts " + error);
      }
    });
  },

  fetchContacts: function() {
    if(User.userLogin === 0) {
      return 0;
    }

    var url = ""
    if(gid === 0) {
      url = "/fetch?service=contacts"
    }
    else {
      url = "/fetch?service=contacts&gid=" + gid
    }

    $.ajax({
      url: url,
      cache: false,
      dataType: "json",
      success: function(obj){
        var i = 0;
        var str;

        if(obj.msg === "Success") {
          str = '<select id="contacts" class="multiselect" multiple="multiple" name="contacts[]">';
          for(i=0; i<obj.data.length; i++) {
            str += '<option value=' + obj.data[i].email + '>' + 
                obj.data[i].name + '</option>';
          }
          str += '</select>';

          $("#sharecontacts").html(str);
          writeDebug(obj.data.length, 3);
          User.userAuth = 1;
        }
        else if(obj.msg === "Authorize") {
          $("#hdrmsg").html("Hello, " + User.userName + " " + obj['data']);
          User.userAuth = 0;
        }
      },
      error: function(error) {
        alert("Could not fetch contacts " + error);
      }
    });
  }

};



function syncInit()
{
  //$("#share_btn").bind('click', showShare);
  //$("#join_btn").bind('click', showJoin);

  User.checkLogin();
  //User.fetchDocs();
  $( "#sharedialog" ).dialog({
    autoOpen: false,
    resizable: false,
    draggable: false,
    modal: true,
    width: 650
  });
  $( "#joindialog" ).dialog({
    autoOpen: false,
    resizable: false,
    draggable: false,
    modal: true,
    width: 650
  });

  //shows when other sends a access request (reqaccess)
  $( "#accessrequest" ).dialog({
    resizable: false,
    draggable: false,
    autoOpen: false,
    width:540,
    modal: false,
    closeOnEscape: false
  });

  //lock the screen, for viewer mode
  $( "#lockscreen" ).dialog({
    resizable: false,
    draggable: false,
    autoOpen: false,
    width:340,
    modal: true,
    position: 'top',
    closeOnEscape: false,
    buttons: {
      "Request Access": function() {
        requestAccess();
      }
    }
  });

}


function showShare()
{
  if(settings.demo === 1) {
    if(User.userType === "EDITOR") {
      $("#sharemsg").html("You are already sharing this session.");
      $("#sharedialog").dialog("option", "buttons",
          {
            "Ok": function() { $(this).dialog("close"); }
          }
      );
    }
    else {
      $("#sharecontacts").hide();
      $("#sharemsg").html("To share this liveBoard sessions please hit the share button. <br><br>");
      $("#sharedialog").dialog("option", "buttons",
          {
            "Share": function() { share(); },
            "Cancel": function() { $(this).dialog("close"); }
          }
      );
      $("#sharectrl").html('<a href="#" onclick="share();" data-role="button" data-theme="b">Share</a>');
    }
    $("#sharedialog").dialog("open");
    return;
  }

  if(User.userLogin == 0 || User.userAuth == 0) {
    $("#sharecontacts").hide();
    $("#sharemsg").html("Please login using your Google account and authorized this app<br><br>");
    $("#sharemsg").append("Google does not share your password with the application");
    $("#sharedialog").dialog("option", "buttons",
        {
          "Ok": function() { $(this).dialog("close"); }
        }
    );
    $("#sharedialog").dialog("open");
    return;
  }

  if(User.userType === "EDITOR") {
    $("#sharemsg").html("You are already sharing this session.");
    $("#sharedialog").dialog("option", "buttons",
      {
        "Ok": function() { $(this).dialog("close"); }
      }
    );
  }
  else {
    $("#sharemsg").html("Please select from your contacts. Use two-finger scroll.");
    $("#sharedialog").dialog("option", "buttons",
      {
        "Share": function() { share(); },
        "Cancel": function() { $(this).dialog("close"); }
      }
    );
    $(".multiselect").multiselect();
    $("#sharecontacts").show();
    $("#sharectrl").html('<a href="#" onclick="share();" data-role="button" data-theme="b">Share</a>');
  }
  $("#sharedialog").dialog("open");
}


function showJoin()
{
  if(settings.demo === 1) {
    if(User.userType === "VIEWER" || User.userType === "EDITOR") {
      $("#joinmsg").html("You are already sharing this session");
      $("#joindialog").dialog("option", "buttons",
          {
            "Ok": function() { $(this).dialog("close"); }
          }
      );
    }
    else {
      $("#joinmsg").html("You will be joined to the session '" + gid + "'");
      $( "#joindialog" ).dialog({
        buttons: {
          "Join": function() { join(); },
          "Cancel": function() { $(this).dialog("close"); }
        }
      });
      $("#joinctrl").html('<a href="#" onclick="join();" data-role="button" data-theme="b">Join</a>');
    }
    $("#joindialog").dialog("open");
    return;
  }

  if(User.userLogin == 0 || User.userAuth == 0) {
    $("#joinmsg").html("Please login using your Google account and authorized this application. <br>");
    $("#joinmsg").append("Google does not share your password with the application. <br>");
    $("#joinmsg").append("<br>If you are already logged in please <b>Click the Join button</b> to join the session");
    $("#joindialog").dialog("option", "buttons",
        {
          "Ok": function() { $(this).dialog("close"); }
        }
    );
    $("#joindialog").dialog("open");
    return;
  }

  if(User.userType === "VIEWER" || User.userType === "EDITOR") {
    $("#joinmsg").html("You are already sharing this session");
    $("#joindialog").dialog("option", "buttons",
        {
          "Ok": function() { $(this).dialog("close"); }
        }
    );
  }
  else {
    $("#joinmsg").html("You will be joined to the session '" + gid + "'");
    $( "#joindialog" ).dialog({
      width:540,
      modal: true,
      buttons: {
        "Join": function() { join(); },
        "Cancel": function() { $(this).dialog("close"); }
      }
    });
    $("#joinctrl").html('<a href="#" onclick="join();" data-role="button" data-theme="b">Join</a>');
  }
  $("#joindialog").dialog("open");
}


function syncSend(subtype)
{
  var data = {
    'type': 'sync',
    'subtype': subtype,
    'groupname': groupname,
    'username': User.userName,
    'gid': gid,
    'uid': User.uid
  };

  if(wsock) {
    wsock.send(JSON.stringify(data));
  }

}


function syncOpen()
{
  if(syncstate === "CONNECTING") {
    syncstate = "CONNECTED";
    if(User.userType === "EDITOR") {
      //send a share message
      syncSend("share");
    }
    else if(User.userType === "VIEWER") {
      //send a join message
      syncSend("join");
    }
  }
}


function syncRecv(data)
{
  //a share message received by others, not normal.
  //in case someone is joined in and the owner loses connection
  //when shared again it would come here. Maybe should avoid 
  //that XXX
  if(data.subtype === "share") {
    alert("How did you get the share message");
  }

  //indicates this user when someone else joins.
  else if(data.subtype === "join") {
    //$("#chat_btn").html("User: " + data.username + " joined");
    syncUser();
  }

  else if(data.subtype === "reqaccess") {
  }

  //unicast response from the server for a share or join request
  else if(data.subtype === "response") {
    if(data.osubtype === "share") {
      if(data.status === "success") {
        //if we successfully got a share response, go ahead
        //and send the id to selected contacts
        User.userType = "EDITOR";
        gid = data.msg;
        if(settings.demo === 1) {
          $("#sharecontacts").hide();
          $("#sharemsg").html("Please send the following link to your contacts with whom you want to share the liveBoard<br><br>");
          $("#sharemsg").append("http://live-board.appspot.com/index.html?demo=1&gid=" + gid);
          $("#sharedialog").dialog("option", "buttons",
              {
                "Ok": function() { $(this).dialog("close"); }
              }
          );
          $("#sharectrl").html("");
          $("#syncstatus").html("Sharing link http://live-board.appspot.com/index.html?demo=1&gid=" + gid);
          return;
        }
        else {
          $("#sharemsg").html("Connected");
          sendShareRequest(gid);
        }
      }
      else {
        syncError(data);
      }
    }
    else if(data.osubtype === "join") {
      if(data.ownername) {
        $("#joinmsg").html(data.msg + "<br>'" + data.ownername + "' is the Editor for the session");
      }
      else {
        $("#joinmsg").html(data.msg + "<br>");
      }
      if(data.status === "success") {
        User.userType = "VIEWER";
        $("#syncstatus").html("Sharing link http://live-board.appspot.com/index.html?gid=" + gid);
        $("#joindialog").dialog("option", "buttons",
            {
              "Ok": function() { $(this).dialog("close"); }
            }
        );
      }
      else {
        $("#joindialog").dialog("option", "buttons",
            {
              "Ok": function() { $(this).dialog("close"); }
            }
        );
      }
      $("#joinctrl").html("");
    }
  }
  else if(data.subtype === "restore") {
    bboxjson = data.bbox;
    g_ObjsJson = data.drawobjs;
    LB.Canvas.restore();
  }
}


function syncError(data)
{
  $("#syncmessage").html("Connection Error");
  if(User.userType === "EDITOR") {
    $("#sharecontacts").hide();
    $("#sharemsg").html("Failed to connect. Please try again in a few seconds.<br>");
    $("#sharedialog").dialog("option", "buttons",
        {
          "Ok": function() { $(this).dialog("close"); }
        }
    );
  }
  else if(User.userType === "VIEWER") {
    $("#joinmsg").html("Failed to connect. Please try again later.<br>" + 
        "You can still use the whiteboard and save the files locally");
    $("#joindialog").dialog("option", "buttons",
        {
          "Ok": function() {
            $(this).dialog("close");
          }
        }
    );
  }
  User.userType = "";
}

function syncClose(data)
{
  //indicates already connect socket got disconnected
  if(syncstate === "CONNECTED") {
    $("#syncmessage").html("You got disconnected from the server");
    if(User.userType === "VIEWER") {
      unlockScreen();
    }
  }
  syncError(data);
  //$("#chat_btn").html("Not Sharing");
  syncstate = "DISCONNECTED";
  User.userType = "";
}


function shareSuccess(msg) {
  $("#sharemsg").html(msg);
  $("#sharecontacts").hide();
  $("#sharedialog").dialog("option", "buttons",
      {
        "Ok": function() {
          $(this).dialog("close");
        }
      }
  );
}

function sendShareRequest(gid) {
    var i = 0;
    var str = '';
    var obj = new Object();
    var selected = [];

    $("#syncstatus").html("Sharing link http://live-board.appspot.com/index.html?gid=" + gid);
    //$("#chat_btn").html("Sharing");

    for(i=0; i<contacts.length; i++) {
      if(contacts[i].selected === true) {
        str += contacts[i].value + " ";
        selected.push(contacts[i].value);
      }
    }
    obj['contacts'] = selected;
    obj['link'] = "gid=" + gid;

    str += "Please send the following link to your shared contacts<br>";
    str += "You can email them from here by hitting Email below<br><br>";
    str += "http://live-board.appspot.com/index.html?gid=" + gid;
    $("#sharemsg").html(str);
    $("#sharedialog").dialog("option", "buttons",
        {
          "Email": function() {
            $.ajax({
              type: "POST",
              url: "/sharereq",
              cache: false,
              data: JSON.stringify(obj),
              success: shareSuccess,
              error: function(error) {
                $("#sharemsg").html("Could not share the link. Please send it manually<br>");
                $("#sharemsg").append(gid);
              }
            });
          },
          "Cancel": function() {
            $(this).dialog("close");
          }
        }
    );
}

function accessRequested(user) {
  $("#accessrequest").html("'" + user + "' is requesting access");
  $("#accessrequest").dialog("option", "buttons", 
    {
      "Grant Access": function() {
        grantAccess(user);
      },
      "Deny Access": function() {
        denyAccess(user);
      }
    }
  );
  $("#accessrequest").dialog( "open" );
}

function grantAccess(to) {
  $("#accessrequest").dialog( "close" );
  var data = {
    'type': 'sync',
    'msg': 'grantaccess',
    'to': to,
    'groupname': gid,
    'user': username
  }

  if(wsock) {
    wsock.send(JSON.stringify(data));
  }
  lockScreen("'" + to + "' is the Editor of the whiteboard");
}


function denyAccess(to) {
  $("#accessrequest").dialog( "close" );
  var data = {
    'type': 'sync',
    'msg': 'denyaccess',
    'to': to,
    'groupname': gid,
    'user': username
  }

  if(wsock) {
    wsock.send(JSON.stringify(data));
  }
  $("#syncmessage").html("You are now the owner of this shared session");
  $("#syncstatus").html("Sharing (Editor)");
}



function lockScreen(msg) {
  $("#lockscreen").html(msg);
  $("#lockscreen").dialog( "open" );
  $("#syncmessage").html("You are now joined to the shared sesion");
  $("#syncstatus").html("Sharing (Viewer)");
}


function unlockScreen() {
  $("#lockscreen").dialog( "close" );
  $("#syncmessage").html("You are now the owner of this shared session");
  $("#syncstatus").html("Sharing (Editor)");
}

function requestAccess() {
  //send a req access msg
  var data = {
    'type': 'sync',
    'subtype': 'reqaccess',
    'groupname': groupname,
    'username': username,
    'gid': gid,
    'uid': uid
  }

  $( "#lockscreen" ).html("Requesting Access ... ");

  if(wsock) {
    wsock.send(JSON.stringify(data));
  }
}


function syncUser() {
    LB.DB.saveDB();
    var data = {
      'type': 'sync',
      'subtype': 'restore',
      'groupname': groupname,
      'username': username,
      'gid': gid,
      'uid': uid,
      'bbox': bboxjson,
      'drawobjs': g_ObjsJson
    }

    if(wsock) {
      wsock.send(JSON.stringify(data));
    }
}

function share() {
  $("#sharemsg").html("Connecting ... <br> ");
  User.userType = "EDITOR";
  wsock = new WSocket("ws://50.18.25.29:12345/");
  syncstate = "CONNECTING";
}


function join() {

  $("#joinmsg").html("Connecting ... ");
  User.userType = "VIEWER";
  wsock = new WSocket("ws://50.18.25.29:12345/");
  syncstate = "CONNECTING";
}
